/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.persistence.EntityManager;
import Bean.Professor;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import util.JPAUtil;

/**
 *
 * @author alexandre
 */
@Stateless(name="ProfDAO")
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class ProfDAO {
    
    
    @PersistenceContext(unitName = "PersistenceUnit")
    private EntityManager em;
    @Resource
    private SessionContext context;//Session context que monitora se algum erro ocorre para fazer rollback
    
    public void add(Professor prof){
       // EntityManager em = JPAUtil.getInstance().getEntityManager();
      try
      {
          em.persist(prof);
      }
      catch(Exception e){
          
          e.printStackTrace();
      }
    }
    
    public void edit(Professor prof){
        //EntityManager em = JPAUtil.getInstance().getEntityManager();
        em.merge(prof);
    }
    
    public void del(Professor prof){
     //   EntityManager em = JPAUtil.getInstance().getEntityManager();
        Professor prof2 = em.merge(prof);
        em.remove(prof2);
    }
    
    public List<Professor> getAllProfessor(){
        //return JPAUtil.getInstance().getList(Professor.class, "SELECT prof FROM Professor prof");
       Query query = em.createQuery("select prof from Professor prof");
       List<Professor> prof =  query.getResultList();
        
        
        return prof;
    }
    
    public Professor getProfessorID(int id){
        Professor prof = em.find(Professor.class, id);
        return prof;
        //return JPAUtil.getInstance().getEntity(Professor.class, id);
    }
    
    public List<Professor> getRetornaProfPorEscola(int id){
        Query query = em.createQuery("select prof from Professor prof where prof.escola.id=:id");
        query.setParameter("id", id);
        List<Professor> prof =  query.getResultList();
        
        
        return prof;
    }
    
    public  List<Professor> getAlunoByID(int id){
      
           List toReturn = null;
           Query query = em.createQuery("select aluno From Aluno aluno where id:=" + id + "");
           query.setParameter("id", id);
           toReturn = query.getResultList();
        return toReturn;
        }
}
